package edu.scau.mis.web.controller.pos;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.scau.mis.core.annotation.RequestLog;
import edu.scau.mis.core.domain.AjaxResult;
import edu.scau.mis.core.enums.BusinessType;
import edu.scau.mis.pos.domain.Category;
import edu.scau.mis.pos.domain.ProductDescription;
import edu.scau.mis.pos.service.IProductService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    private IProductService productService;

    @RequestLog(title = "通过id查询产品",businessType = BusinessType.GET)
    @GetMapping("/getBySn/{productSn}")
    @ApiOperation("根据SN找产品")
    public AjaxResult getBySn(@PathVariable("productSn") String productSn){
        return AjaxResult.success(productService.getProductByProductSn(productSn));
    }

    @RequestLog(title = "列出所有产品",businessType = BusinessType.GET)
    @GetMapping("/listAll")
    @ApiOperation("列出所有产品")
    public AjaxResult listAll(){
        return AjaxResult.success(productService.listAllProduct());
    }

    @RequestLog(title = "查询产品列表",businessType = BusinessType.GET)
    @GetMapping("/list")
    @ApiOperation("查询产品列表")
    public AjaxResult list(ProductDescription product) {
        List<ProductDescription> list = productService.selectProductList(product);
        return AjaxResult.success(list);
    }

    @RequestLog(title = "查询产品详情",businessType = BusinessType.GET)
    @GetMapping(value = "/{productId}")
    @ApiOperation("查询产品详情")
    public AjaxResult get(@PathVariable("productId") Long productId) {
        return AjaxResult.success(productService.selectProductById(productId));
    }

    @RequestLog(title = "新增产品",businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增产品")
    public AjaxResult add(@RequestBody ProductDescription product) {
        int rows = productService.insertProduct(product);
        return rows > 0 ? AjaxResult.success("添加产品成功") : AjaxResult.error("添加产品失败");
    }

    @RequestLog(title = "修改产品",businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改产品")
    public AjaxResult edit(@RequestBody ProductDescription product) {
        int rows = productService.updateProduct(product);
        return rows > 0 ? AjaxResult.success("修改产品成功") : AjaxResult.error("修改产品失败");
    }

    //    @DeleteMapping("/{productId}")
//    @ApiOperation("删除产品")
//    public AjaxResult remove(@PathVariable Long productId) {
//        int rows = productService.deleteProductById(productId);
//        return rows > 0 ? AjaxResult.success("删除产品成功") : AjaxResult.error("删除产品失败");
//    }
    @RequestLog(title = "批量删除产品",businessType = BusinessType.DELETE)
    @DeleteMapping("/{productId}")
    @ApiOperation("批量删除产品")
    public AjaxResult remove(@PathVariable Long[] productId) {
        int rows = productService.deleteProductByIds(productId);
        return rows > 0 ? AjaxResult.success("批量删除产品成功") : AjaxResult.error("删除产品失败");
    }

    @RequestLog(title = "分页查询",businessType = BusinessType.GET)
    @GetMapping("/page")
    @ApiOperation("分页查询")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, ProductDescription product) {
        PageHelper.startPage(pageNum,pageSize);
        List<ProductDescription> list = productService.selectProductList(product);
        PageInfo<List> pageInfo = new PageInfo(list);
        // 以下写法也可以
        // PageInfo<ProductDescription> pageInfo = new PageInfo<>(list)
        return AjaxResult.success(pageInfo);
    }
    /**
     * Excel批量导出数据
     */
    @RequestLog(title = "Excel批量导出数据",businessType = BusinessType.OTHER)
    @GetMapping("/export")
    @ApiOperation("Excel批量导出数据")
    public void exportData(@RequestParam(required = false) String productName,
                           HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 第一种全部导出
        List<ProductDescription> list = new ArrayList<>();
        if (StrUtil.isBlank(productName)) {
            list = productService.listAllProduct(); //查询出product表的所有数据
        }
        //获取所有数据对象
        writer.write(list,true);

        response.setContentType("application/vnd.openxmlformats-officedocunment.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("产品信息表","UTF-8")+".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        //刷新到输出流,写完后关闭流
        writer.flush(outputStream,true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }

    /**
     * Excel批量导入数据
     * */
    @RequestLog(title = "Excel批量导入数据",businessType = BusinessType.OTHER)
    @PostMapping("/excel/upload")
    @ApiOperation("Excel批量导入数据")
    public AjaxResult upload(MultipartFile file) throws IOException{
        List<ProductDescription> infoList = ExcelUtil.getReader(file.getInputStream()).readAll(ProductDescription.class);
        if(!CollectionUtil.isEmpty(infoList)){
            for(ProductDescription productDescription : infoList) {
                try {
                    productService.insertProduct(productDescription);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return AjaxResult.success("上传成功");
    }
}